package edu.cmu.cs.webapp.ioms.actions.product;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.ProductDAOImpl;
import edu.cmu.cs.webapp.ioms.logging.Alerts;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.views.OrderDetailsView;
import edu.cmu.cs.webapp.ioms.views.ProductView;

/**
 * @author Christian
 * 
 */
public class DeleteProductViewAction implements IViewActionDelegate {
	private Product _model;
	private ProductView _view;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		this._view = (ProductView) view;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		if (this._model != null) {

			if (MessageDialog
					.openConfirm(this._view.getViewSite().getShell(),
							"Delete Confirmation",
							"Are you sure you want to delete this product from your system?")) {
				try {
					new ProductDAOImpl().deleteProd(_model);

					this._view.refreshProductsView();

				} catch (DataAccessException e) {
					Alerts.getInstance().detailError("Data Access Error",
							e.getLocalizedMessage(), e);
				}
			}

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof Product) {
				this._model = (Product) obj;
			}
		}
	}

}
